package ar.edu.sovietrussia.customcomponents.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.apache.wicket.Component;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;

/**
 */
public abstract class InwardReplaceablePanel extends Panel {

    private static final long serialVersionUID = 1L;

    public InwardReplaceablePanel(final String id) {
        super(id);
    }

    public InwardReplaceablePanel(final String id, final IModel model) {
        super(id, model);
    }

    public void goBack(final Class<?> clazz) {

        // IMPORTANTE ACLARACION: este metodo sirve para instanciar el
        // componente
        // anterior a este. Es un poco complicadin, pero funciona :)

        Class<?>[] classes = new Class[1];
        classes[0] = String.class;

        Constructor<?> replacingComponent = null;

        try {
            replacingComponent = clazz.getConstructor(classes);
        } catch (SecurityException e) {
            throw new UnsupportedOperationException("Tire una Security Exception", e);
        } catch (NoSuchMethodException e) {
            throw new UnsupportedOperationException("Tire un NoSuchMethodException", e);
        }

        try {
            replaceWith((Component) replacingComponent.newInstance(getId()));
        } catch (IllegalArgumentException e) {
            throw new UnsupportedOperationException("Tire una IllegalArgument Exception", e);
        } catch (InstantiationException e) {
            throw new UnsupportedOperationException("Tire una Instantiation Exception", e);
        } catch (IllegalAccessException e) {
            throw new UnsupportedOperationException("Tire una IllegalAccess Exception", e);
        } catch (InvocationTargetException e) {
            throw new UnsupportedOperationException("Tire una InvocationTarget Exception", e);
        }
    }

}
